﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HtmlAgilityPack;
using Newtonsoft.Json.Linq;
using YuuzleComic.DALFactory;
using System.Net;

public partial class yzadmin_data_collect_52tian : YuuzleComic.Web.UI.ManagePage
{
    protected string json = "";
    private string domain = "http://www.tianshangrenjian123.com";
    private string baseUrl = "http://www.tianshangrenjian123.com/gengxin/";
    private string searchUrl = "http://www.tianshangrenjian123.com/search.asp?searchType={0}&keyword={1}";
    private JObject result = new JObject();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            switch (Request["a"])
            {
                case "list":
                    this.ProcessList();
                    break;
                case "single":
                    this.ProcessSingle();
                    break;
                case "import":
                    this.ProcessImport();
                    break;
                default:
                    break;
            }
        }
    }

    private void ProcessImport()
    {
        try
        {
            HtmlWeb webClient = this.getWebClient();
            string[] urlArray = Request["zjurl"].Split('\n');
            Array.Reverse(urlArray);//数组倒序
            foreach (string url in urlArray)
            {
                HtmlDocument doc = webClient.Load(url);
                string path = doc.DocumentNode.SelectSingleNode("//div/script[@language='javascript' and @type='text/javascript']").InnerText.Split(new string[] { "=\"", "\";" }, StringSplitOptions.None)[1];
                HtmlNodeCollection pages = doc.GetElementbyId("pageSelect").SelectNodes("option");
                List<string> tpurl = new List<string>();
                foreach (HtmlNode page in pages)
                {
                    tpurl.Add("/comic/" + path + page.Attributes["value"].Value + ".jpg");
                }
                YuuzleComic.Model.zj zj = new YuuzleComic.Model.zj();
                zj.cid = Convert.ToInt32(Request["id"]);
                zj.zjmc = doc.DocumentNode.SelectSingleNode("//h2").InnerText.Replace(doc.DocumentNode.SelectSingleNode("//h1").InnerText,"");
                zj.time = DateTime.Now;
                zj.isdownload = false;
                zj.tpadd = Request["tpadd"] + zj.zjmc + "/";
                zj.tps = tpurl.Count;
                zj.tpurl = string.Join("|", tpurl.ToArray());
                YuuzleComic.BLL.zj zjbll = new YuuzleComic.BLL.zj();
                if (urlArray.Length == 1 && !string.IsNullOrEmpty(Request["zjid"]))
                {
                    zj.id = int.Parse(Request["zjid"]);
                    zjbll.Update(zj);
                }
                else
                {
                    zjbll.Add(zj);
                }
            }
            result.Add("success", true);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }
    }

    private void ProcessSingle()
    {
        try
        {
            HtmlWeb webClient = this.getWebClient();
            HtmlDocument doc = webClient.Load(Request["url"]);
            HtmlNode infoNode = doc.DocumentNode.SelectSingleNode("//div[@class='insideright margintop']");
            HtmlNodeCollection attrNodes = infoNode.SelectNodes("div//div[starts-with(@class,'sectioninfo')]/p");
            result.Add("mhmc", attrNodes[0].SelectSingleNode("span").InnerText);
            result.Add("mhfm", infoNode.SelectSingleNode("div//img[1]").Attributes["src"].Value);
            result.Add("zzmc", attrNodes[1].SelectSingleNode("span").InnerText.Replace("&nbsp;", ","));
            result.Add("zt", attrNodes[2].SelectSingleNode("span").InnerText);
            result.Add("zm", attrNodes[8].SelectSingleNode("span[2]").InnerText);
            result.Add("diqu", attrNodes[7].SelectSingleNode("span[2]").InnerText);
            result.Add("time", attrNodes[10].SelectSingleNode("span[2]").InnerText);
            result.Add("mhjj", infoNode.SelectSingleNode("div//div[@class='gray']").InnerText.Trim());
            result.Add("mhjs", infoNode.SelectSingleNode("div//div[@class='gray']").InnerHtml);
            result.Add("mhtc", attrNodes[3].SelectSingleNode("span").InnerText);
            JArray chapters = new JArray();
            HtmlNodeCollection nodes = doc.GetElementbyId("mhlist").SelectNodes("ul[1]/li");
            if (nodes != null)
            {
                foreach (HtmlNode item in nodes)
                {
                    JObject chapter = new JObject();
                    chapter.Add("zjmc", item.SelectSingleNode("a").InnerText);
                    chapter.Add("zjurl", Request["url"] + item.SelectSingleNode("a").Attributes["href"].Value);
                    chapters.Add(chapter);
                }
            }
            result.Add("chapters", chapters);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }
    }

    private void ProcessList()
    {
        try
        {
            HtmlWeb webClient = this.getWebClient();
            //HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class='lettercontent' or @class='lettercontenta']");
            JArray data = new JArray();
            if (Request["query"] == null || string.IsNullOrEmpty(Request["query"].Trim()))
            {
                HtmlDocument doc = webClient.Load(baseUrl);
                HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class='updateList margintop']/ul/li");
                foreach (HtmlNode node in nodes)
                {
                    JObject jo = new JObject();
                    jo.Add("mhmc", node.SelectSingleNode("a[1]").InnerText);
                    jo.Add("mhurl", domain + node.SelectSingleNode("a[1]").Attributes["href"].Value);
                    jo.Add("zjmc", node.SelectSingleNode("a[2]") != null ? node.SelectSingleNode("a[2]").InnerText : "");
                    jo.Add("time", node.SelectSingleNode("span[1]").InnerText);
                    data.Add(jo);
                }
            }
            else
            {
                HtmlDocument doc = webClient.Load(string.Format(searchUrl, new string[] { "cartoonName", Request["query"].Trim() }));
                HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class='endcomicscontent center loadlist']/ul/li");
                if (nodes == null)
                {
                    doc = webClient.Load(string.Format(searchUrl, new string[] { "cartoonAuthor", Request["query"].Trim() }));
                    nodes = doc.DocumentNode.SelectNodes("//div[@class='endcomicscontent center loadlist']/ul/li");
                }
                foreach (HtmlNode node in nodes)
                {
                    JObject jo = new JObject();
                    jo.Add("mhmc", node.SelectSingleNode("div[2]/h1/a[1]").InnerText);
                    jo.Add("mhurl", domain + node.SelectSingleNode("div[2]/h1/a[1]").Attributes["href"].Value);
                    jo.Add("zzmc", node.SelectSingleNode("div[2]/p[1]/span[1]/a[1]").InnerText);
                    jo.Add("zjmc", node.SelectSingleNode("div[2]/h1/a[2]") != null ? node.SelectSingleNode("div[2]/h1/a[1]").InnerText : "");
                    data.Add(jo);
                }
            }
            result.Add("data", data);
            result.Add("total", data.Count);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }

    }

    private HtmlWeb getWebClient() {
        HtmlWeb webClient = new HtmlWeb();
        HtmlAgilityPack.HtmlWeb.PreRequestHandler handler = delegate(HttpWebRequest request)
        {
            request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            request.CookieContainer = new System.Net.CookieContainer();
            request.Timeout = 500000;
            return true;
        };
        webClient.PreRequest += handler;
        return webClient;
    }
}